package cn.itcast.itcaststore.web.servlet.manager;

import cn.itcast.itcaststore.domain.Products;
import cn.itcast.itcaststore.exception.FindProductByIdException;
import cn.itcast.itcaststore.serive.ProductService;
import cn.itcast.itcaststore.serive.impl.ProductServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 根据商品id查找指定商品信息的servlet
 */
@WebServlet("/admin/findProductById")
public class FindProductByIdServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 获取商品的Id
        String id = request.getParameter("id");
        // 获取type参数值，此处的type用于区分请求来自前台网站还是后台系统
        String type = request.getParameter("type");
        // 创建service 层对象
        ProductService service = new ProductServiceImpl();
        try {
            // 调用service层方法，通过id查找商品
            Products p = service.findProductById(id);
            request.setAttribute("p",p);
            // 前台网站不传递type值，会跳转到前台网站的详细信息info.jsp页面
            if (type == null){
                request.getRequestDispatcher("/client/info.jsp").forward(request,response);
                return;
            }
            // 如果请求来自后台系统，跳转到后台系统的商品编辑edit.jsp页面
            request.getRequestDispatcher("/admin/products/edit.jsp").forward(request,response);
            return;
        }catch (FindProductByIdException e){
            e.printStackTrace();
        }
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request,response);
    }
}
